package me.leiusual.sharing.ui.shop

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_shop_business.*
import me.leiusual.sharing.R
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.ui.shop.adapter.ShopBusinessAdapter
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-29
 * description:
 */
class ShopBusinessFragment : DaggerFragment() {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: ShopBusinessViewModel by viewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_shop_business, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    recycler_view.adapter = ShopBusinessAdapter {
      Timber.v("点击：%s", it)

      val action = ShopBusinessFragmentDirections.actionShopBusinessFragmentToShopBusinessLevelFragment(it.businessType)
      findNavController().navigate(action)
    }

    observeData()
    viewModel.businessType()
  }

  private fun observeData() {
    viewModel.businessType.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("businessType = %s", it)
      when (it) {
        is Data.Loading -> {
          state_constraint_layout.showProgress()
        }
        is Data.Error -> {
          state_constraint_layout.showError(it.error.message)
        }
        is Data.Success -> {
          state_constraint_layout.showContent()

          val adapter = recycler_view.adapter as ShopBusinessAdapter
          adapter.submitList(it.data)
        }
      }
    })
  }
}